package com.mk.aop;

import com.mk.annotation.AuthCheck;
import com.mk.common.ThreadLocalUtil;
import com.mk.contants.UserConstant;
import com.mk.exception.BusinessException;
import com.mk.exception.ErrorCode;
import com.mk.model.entity.User;
import com.mk.model.enums.UserRoleEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AuthInterceptor {

    /**
     * 执行拦截
     *
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     */
    @Around("@annotation(authCheck)") // 访问添加该注解的接口，必须登录
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String role = authCheck.value();
        // 当前登录用户
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        // 未登录，抛异常
        if (loginUser == null)
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(role);
        // 不需要权限，放行
        if (mustRoleEnum == null || UserRoleEnum.PUBLIC.equals(mustRoleEnum)) {
            return joinPoint.proceed();
        }
        // 以下为：必须有该权限才通过
        // 获取当前用户具有的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        // 没有权限，拒绝
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "用户权限不合法");
        }
        // 要求必须有管理员权限，但用户没有管理员权限，拒绝
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}
